﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Travianer.IController;
using System.Net;
using System.IO;
using System.IO.Compression;

namespace Travianer.Controller.WebRequestController
{
    public class HandleController : IHandleController
    {
        public void Login(string strServerLocation, string strUserName, string strPassword, params object[] para)
        {
            HttpWebRequest request = System.Net.WebRequest.Create(strServerLocation) as HttpWebRequest;
            CookieContainer cookie = request.CookieContainer;
            request.Referer = strServerLocation;
            request.Accept = "Accept-Encoding:gzip,deflate,sdch";
            request.KeepAlive = true;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            Encoding encoding = Encoding.UTF8;
            byte[] postData = Encoding.UTF8.GetBytes(string.Format("name={0}&pass={1}", strUserName, strPassword));

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            if (response.Headers["Content-Encoding"] != null && response.Headers["Content-Encoding"].ToLower().Contains("gzip"))
            {
                responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
            }

            StreamReader streamReader = new StreamReader(responseStream, encoding);
            string retString = streamReader.ReadToEnd();

            streamReader.Close();
            responseStream.Close();

            request = (HttpWebRequest)System.Net.WebRequest.Create(strServerLocation+"village1.php");
            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream GetStream = response.GetResponseStream();
                StreamReader GetStreamReader;
                GetStreamReader = new StreamReader(GetStream, System.Text.Encoding.GetEncoding("utf-8"));
                retString = GetStreamReader.ReadToEnd();
                GetStreamReader.Close();
                GetStream.Close();
            }
        }
    }
}
